package com.ruoyi.settled.service;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.ruoyi.settled.domain.AlipayConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AlipayService {

    private final AlipayConfig alipayConfig;

    @Autowired
    public AlipayService(AlipayConfig alipayConfig) {
        this.alipayConfig = alipayConfig;
    }

    public String createPayment(String outTradeNo, String totalAmount, String subject) {
        try {
            AlipayClient alipayClient = new DefaultAlipayClient(
                    alipayConfig.getGatewayUrl(),
                    alipayConfig.getAppId(),
                    alipayConfig.getMerchantPrivateKey(),
                    "json",
                    "UTF-8",
                    alipayConfig.getAlipayPublicKey(),
                    "RSA2"
            );

            AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
            request.setReturnUrl(alipayConfig.getReturnUrl());
            request.setNotifyUrl(alipayConfig.getNotifyUrl());

            String bizContent = String.format("{" +
                    "\"out_trade_no\":\"%s\"," +
                    "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"," +
                    "\"total_amount\":%s," +
                    "\"subject\":\"%s\"" +
                    "}", outTradeNo, totalAmount, subject);

            request.setBizContent(bizContent);

            AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
            if (response.isSuccess()) {
                return response.getBody();
            } else {
                throw new RuntimeException("支付宝支付请求失败");
            }
        } catch (Exception e) {
            throw new RuntimeException("支付宝支付请求异常", e);
        }
    }
}